package com.khh.helper;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by webrx on 2017-09-04.
 */

public class MybatisHelp<T> {
        private SqlSessionFactory sf;
        private SqlSession ss;
        private Class t;

        public MybatisHelp() {

            try {
                InputStream i = Resources.getResourceAsStream("mybatis-conf.xml");
                this.sf = new SqlSessionFactoryBuilder().build(i);
                this.ss = this.sf.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }



        }
        public MybatisHelp(Class t) {

            try {
                InputStream i = Resources.getResourceAsStream("mybatis-conf.xml");
                this.sf = new SqlSessionFactoryBuilder().build(i);
                this.ss = this.sf.openSession();
                this.t = t;
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        //反回范型getMapper
        public T getMapper(){
            return (T)this.ss.getMapper(this.t);
        }


        //
        public void close() {
            if (this.ss != null) {
                this.ss.commit();
                this.ss.clearCache();
                this.ss.close();
            }
        }

        public SqlSessionFactory getSf() {
            return sf;
        }

        public void setSf(SqlSessionFactory sf) {
            this.sf = sf;
        }

        public SqlSession getSs() {
            return ss;
        }

        public void setSs(SqlSession ss) {
            this.ss = ss;
        }


}

